package com.jm.bishe.service.Impl;

import com.alibaba.fastjson.JSON;
import com.auth0.jwt.JWT;
import com.jm.bishe.entity.*;
import com.jm.bishe.mapper.*;
import com.jm.bishe.service.RoomService;
import com.jm.bishe.utils.JwtTokenUtil;
import com.jm.bishe.utils.RedisUtil;
import com.jm.bishe.utils.VoUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.sql.Blob;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Random;

@Service
@Slf4j
public class RoomServiceImpl implements RoomService {

    @Autowired
    private RoomMapper roomMapper;
    @Autowired
    private SuperAdminMapper superAdminMapper;
    @Autowired
    private PermissionServiceImpl permissionService;
    @Autowired
    private ReserveMapper reserveMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private OrderMapper orderMapper;

    public Result addRoom(RoomAdd roomAdd, String userId) {
        if (permissionService.queryPermission(userId, 4)) {
            return Result.falure(2029, "你没有该权限", null);
        }
        if (!VoUtil.allFieldIsNULL(roomAdd)) {
            Room room1 = roomMapper.queryRoomById(roomAdd.getRoomId());
            if (room1 == null) {
                byte[] blob = roomAdd.getRoomImg().getBytes(StandardCharsets.UTF_8);
                Room room = new Room(roomAdd.getRoomId(), roomAdd.getRoomPrice()
                        , roomAdd.getRoomType(), 0, 0, blob);
                int i = roomMapper.addRoom(room);
                if (i != 1) {
                    return Result.falure(1001, "添加失败,请联系管理员", null);
                }
                return Result.success("添加成功", null);
            }
            return Result.falure(1008, "房间已存在", null);

        }
        return Result.falure(1003, "数据格式错误，请正确输入", null);
    }

    @Override
    public Result queryAllRoom(String userId) {
        if (permissionService.queryPermission(userId, 1)) {
            return Result.falure(2029, "你没有该权限", null);
        } else {
            List<Room> rooms = roomMapper.queryAllRoom();
            return Result.success("查询成功", JSON.toJSON(rooms));
        }
    }

    @Override
    public Result queryRoomByType(String roomType, String userId) {
        if (permissionService.queryPermission(userId, 1)) {
            return Result.falure(2029, "你没有该权限", null);
        } else {
            List<Room> rooms = roomMapper.queryRoomByType(roomType);
            return Result.success("查询成功", JSON.toJSON(rooms));
        }

    }

    @Override
    public Result queryRoomById(String roomId, String userId) {
        if (permissionService.queryPermission(userId, 1)) {
            return Result.falure(2029, "你没有该权限", null);
        }
        Room room = roomMapper.queryRoomById(roomId);
        if (room == null) {
            return Result.falure(1003, "查询不到该房间", null);
        }
        return Result.success("查询成功", JSON.toJSON(room));
    }

    @Override
    public Result reserveRoom(RoomReserve roomReserve, String userId) {
        if (permissionService.queryPermission(userId, 1)) {
            return Result.falure(2029, "你没有该权限", null);
        }
        roomReserve.setOrderId("order" + System.currentTimeMillis());
        System.out.println(roomReserve);
        String orderUserId = userMapper.queryUserIdByNameAndIDNumber(roomReserve.getOrderUserName(), roomReserve.getOrderUserIDNumber());
        roomReserve.setOrderUserId(orderUserId);
        int i = reserveMapper.reserveRoom(roomReserve);
        if (i != 1) {
            return Result.falure(1001, "预约失败", null);
        }
        return Result.success("预约成功", JwtTokenUtil.getToken(userId));
    }

    @Override
    public Result lockRoom(boolean lock, String roomId, String userId) {
        if (permissionService.queryPermission(userId, 2)) {
            return Result.falure(2029, "你没有该权限", null);
        }
        if (lock) {
            if (roomMapper.queryLocking(roomId) == 0) {
                if (roomMapper.lockRoom(1, roomId) == 1) {
                    return Result.success("锁定成功", JwtTokenUtil.getToken(userId));
                }
                return Result.falure(1001, "锁定失败", null);
            }
            return Result.falure(1008, "该房间已经是锁定状态", null);
        }else {
            if (roomMapper.queryLocking(roomId) == 1) {
                if (roomMapper.lockRoom(0, roomId) == 1) {
                    return Result.success("解锁成功", JwtTokenUtil.getToken(userId));
                }
                return Result.falure(1001, "解锁失败", null);
            }
            return Result.falure(1008, "该房间已经是解锁状态", null);
        }
    }

    @Override
    public Result createDiscount(int number,double price ,String roomType,String userId) {
        if (permissionService.queryPermission(userId, 2)) {
            return Result.falure(2029, "你没有该权限", null);
        }
        List<String> rooms = roomMapper.queryRoomAvailable(roomType);
        if (rooms.size() < number){
            return Result.falure(1003,"没有足够的可用房间",null);
        }
        List randomNumList = getRandomNumList(number, 0, rooms.size());
        List<String> discoutRooms = new ArrayList<>();
        for (Object o : randomNumList) {
            int roomIdIndex = (int) o;
            discoutRooms.add(rooms.get(roomIdIndex));
            redisUtil.set(rooms.get(roomIdIndex), price);
        }
        redisUtil.set("discountRoomList",discoutRooms);
        return Result.success("生成特价房成功",JwtTokenUtil.getToken(userId));
    }

    @Override
    public Result queryDiscount(String id) {
        if (permissionService.queryPermission(id, 1)) {
            return Result.falure(2029, "你没有该权限", null);
        }
        List<Room> roomList = new ArrayList<>();
        List<String> roomIdList = (List<String>) redisUtil.get("discountRoomList");
        if (roomIdList==null){
            return Result.falure(1003,"暂未有特价房",null);
        }
        for (String s : roomIdList) {
            String roomPrice = String.valueOf((double) redisUtil.get(s));
            Room room = roomMapper.queryRoomById(s);
            if (room != null) {
                room.setRoomPrice(roomPrice);
                roomList.add(room);
            }
        }
        return Result.success("查询成功",roomList);
    }

    @Override
    public Result roomCheckIn(String roomId, String realName, String IDNumber, String id) {
        if (permissionService.queryPermission(id, 1)) {
            return Result.falure(2029, "你没有该权限", null);
        }
        String userId = userMapper.queryUserIdByNameAndIDNumber(realName, IDNumber);
        if (userId == null) {
            return Result.falure(1003, "没有该用户", null);
        }
        Room room = roomMapper.queryRoomById(roomId);
        if (room == null) {
            return Result.falure(1003, "没有该房间", null);
        }
        if (room.getIsLocking() == 1) {
            return Result.falure(1003, "该房间已被锁定", null);
        }
        if (room.getIsCheckIn() == 1) {
            return Result.falure(1003, "该房间已被入住", null);
        }
        String roomDiscountPrice = String.valueOf(redisUtil.get(roomId));
        if (!roomDiscountPrice.equals("null")) {
            int order = orderMapper.createOrder(new Order(String.valueOf(System.currentTimeMillis()), roomId, roomDiscountPrice, userId, false, false, null));
            if (order == 1) {
                int i = roomMapper.roomCheckIn(1, roomId);
                if (i != 1) {
                    return Result.falure(1001, "订单创建失败", null);
                }
                return Result.success("订单创建成功", JwtTokenUtil.getToken(id));
            }
        }
        String roomPrice = roomMapper.queryPrice(roomId);
        if (!roomPrice.equals("")) {
            int order = orderMapper.createOrder(new Order(String.valueOf(System.currentTimeMillis()), roomId, roomPrice, userId, false, false, null));
            if (order == 1) {
                int i = roomMapper.roomCheckIn(1, roomId);
                if (i != 1) {
                    return Result.falure(1001, "订单创建失败", null);
                }
                return Result.success("订单创建成功", JwtTokenUtil.getToken(id));
            }
            return Result.falure(1001, "订单创建失败", null);
        }
        return Result.falure(1001, "订单创建失败", null);
    }


    public static List getRandomNumList(int nums,int start,int end){
        //1.创建集合容器对象
        List list = new ArrayList();

        //2.创建Random对象
        Random r = new Random();
        //循环将得到的随机数进行判断，如果随机数不存在于集合中，则将随机数放入集合中，如果存在，则将随机数丢弃不做操作，进行下一次循环，直到集合长度等于nums
        while(list.size() != nums){
            int num = r.nextInt(end-start) + start;
            if(!list.contains(num)){
                list.add(num);
            }
        }

        return list;
    }


}
